<template>
  <!--  库存详情-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" label-width="80">
        <el-form-item label="部门仓库">
          <el-tree-select v-model="searchParam.warehouseId" :data="wareList" check-strictly clearable filterable
                          :render-after-expand="false" :props="{
              children: 'sonList',
              label: 'warehouseName',
              value: 'id',
            }" style="width: 250px" @change="wareChange"/>
        </el-form-item>
        <el-form-item label="工序库位">
          <el-select v-model="searchParam.storageId" placeholder="请选择" clearable filterable style="width: 250px"
                     @change="getList">
            <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="加工属性">
          <el-select v-model="searchParam.processingStatus" placeholder="请选择" clearable filterable style="width: 250px"
                     @change="getList">
            <el-option v-for="item in materialStatusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="物料状态">
          <el-select v-model="searchParam.materialStatus" placeholder="请选择" clearable filterable style="width: 250px"
                     @change="getList">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable style="width: 250px"
                    @keyup.enter="getList"/>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="searchParam.batchNo" placeholder="请输入批次号" clearable style="width: 250px"
                    @keyup.enter="getList"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>列表信息</div>
        </div>
        <div class="pageTableButView">

          <el-button type="primary" @click="qrCodeChange" :disabled="multipleSelection.length !== 1">追溯码修改</el-button>
          <el-button type="primary" @click="qrCodeSplit" :disabled="multipleSelection.length !== 1">二维码拆分</el-button>
          <el-button type="primary" @click="qrCodePush" :disabled="multipleSelection.length == 0">二维码合并</el-button>
          <el-button type="primary" @click="printClick" :disabled="multipleSelection.length == 0">报工总数打印</el-button>
          <el-button type="primary" @click="printBoxClick" :disabled="multipleSelection.length == 0">箱码打印</el-button>
          <el-button type="primary" @click="traceCodePrint" :disabled="multipleSelection.length == 0">追溯码补打</el-button>
          <el-button type="primary" @click="finishedProductShow" :disabled="multipleSelection.length !== 1">成品包装打印
          </el-button>
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="calc(100vh - 370px)" row-key="id" border
                @selection-change="handleSelectionChange" header-cell-class-name="witheTableHeader" show-summary
                :summary-method="getSummaries">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope"> {{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="批次号" prop="batchNo" min-width="200" show-overflow-tooltip align="center" sortable/>
        <!--				<el-table-column label="物料名称" prop="materialName" min-width="200" show-overflow-tooltip align="center" />-->
        <el-table-column label="物料编码" prop="materialNo" min-width="200" show-overflow-tooltip align="center" sortable/>
        <el-table-column label="数量" prop="count" min-width="150" show-overflow-tooltip align="center" sortable>
          <template #default="scope">
            <div class="canChange" v-if="scope.row.materialStatus == 1" @click="showNumberChange(scope.row)">
              {{ scope.row.count }}
            </div>
            <div v-else>{{ scope.row.count }}</div>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="basicUnit" min-width="150" show-overflow-tooltip align="center" sortable/>
        <el-table-column label="仓库名称" prop="warehouseName" min-width="200" show-overflow-tooltip align="center"
                         sortable/>
        <el-table-column label="创建人" prop="createName" align="center" min-width="200" sortable/>
        <el-table-column label="报工人" prop="operatorName" align="center" min-width="200" sortable/>
        <el-table-column label="库位名称" prop="storageName" min-width="200" show-overflow-tooltip align="center"
                         sortable/>
        <el-table-column label="物料状态" prop="materialStatus" align="center" min-width="120" :formatter="formatStatus"
                         sortable/>
        <el-table-column label="加工属性" prop="processingStatus" align="center" min-width="120"
                         :formatter="formatProcessingAttributes" sortable/>
        <el-table-column label="备注" prop="description" min-width="150" show-overflow-tooltip align="center" sortable>
          <template #default="scope">
            <div v-if="scope.row.description" class="canChange" @click="showRemarkEdit(scope.row)">
              {{ scope.row.description }}
            </div>
            <div v-else class="canChange" @click="showRemarkEdit(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="GRN编号" prop="batch" min-width="200" show-overflow-tooltip align="center" sortable/>
        <el-table-column label="生产计划号" prop="planNo" min-width="200" show-overflow-tooltip align="center" sortable/>
        <el-table-column label="炉号" prop="heatNumber" min-width="200" show-overflow-tooltip align="center" sortable/>
        <el-table-column label="追溯码" prop="traceabilityCode" min-width="250" show-overflow-tooltip align="center"
                         sortable/>
        <el-table-column label="转码前追溯码" prop="preorderTraceCode" min-width="250" show-overflow-tooltip align="center"
                         sortable/>
        <el-table-column label="模号" prop="registerName" min-width="150" show-overflow-tooltip align="center" sortable/>

        <el-table-column label="创建时间" prop="createTime" min-width="200" show-overflow-tooltip align="center" sortable/>
        <!--				<el-table-column label="操作" width="200" align="center" fixed="right">-->
        <!--					<template #default="scope">-->
        <!--						<el-dropdown placement="bottom">-->
        <!--							<el-button type="text" size="mini" :icon="Switch"> 物料转换</el-button>-->
        <!--							<template #dropdown>-->
        <!--								<el-dropdown-menu>-->
        <!--									<el-dropdown-item-->
        <!--										v-for="item in materialStatusType"-->
        <!--										:key="item.code"-->
        <!--										@click="materialStatusChange(scope.row,item.code)"-->
        <!--									>-->
        <!--										{{ item.description }}-->
        <!--									</el-dropdown-item>-->
        <!--								</el-dropdown-menu>-->
        <!--							</template>-->
        <!--						</el-dropdown>-->

        <!--						<el-button :icon="DocumentDelete" type="text" size="mini" @click="showRollback(scope.row)"-->
        <!--											 style="margin-left: 10px"> 生产退库-->
        <!--						</el-button>-->
        <!--					</template>-->
        <!--				</el-table-column>-->
        <!--        <el-table-column label="操作" width="200" align="center" fixed="right">-->
        <!--          <template #default="scope">-->
        <!--            <el-button type="text" size="small" :icon="WarningFilled
" @click="handleEdit(scope.row,1)">驳回</el-button>-->
        <!--            <el-button type="text" size="small" :icon="Switch-->
        <!--" @click="doFinish(scope.row)">入库确认-->
        <!--            </el-button>-->
        <!--            &lt;!&ndash;            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>&ndash;&gt;-->
        <!--            &lt;!&ndash;            <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>&ndash;&gt;-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <div class="pagePagination">
        <el-pagination background layout="total,sizes, prev,pager, next" :total="pageTotal" :page-size="pageSize"
                       :current-page="currentPage" @size-change="handleSizeChange"
                       :page-sizes="[10, 20, 50, 100, 200, 500]"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle + '入库单'" width="1000px">
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="工序订单" prop="procedureOrderId">
              <el-select v-model="formData.procedureOrderId" placeholder="请选择工序订单" clearable filterable
                         style="width: 250px" :disabled="popType == 1">
                <el-option v-for="item in procedureOrderList" :key="item.id" :label="item.planNo" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库">
              <el-tree-select v-model="formData.wareId" :data="wareList" :disabled="popType == 1" check-strictly
                              :render-after-expand="false" :props="{
                  children: 'sonList',
                  label: 'warehouseName',
                  value: 'id',
                }" style="width: 250px" @change="wareChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库库位" prop="targetStorageId">
              <el-select v-model="formData.targetStorageId" :disabled="popType == 1" placeholder="请选择"
                         style="width: 250px">
                <el-option v-for="item in storageList" :key="item.id" :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.details" style="width:100% " height="calc(100vh - 600px)">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialId" label="物料编码" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.materialId" :disabled="popType == 1" placeholder="" clearable filterable>
                  <el-option v-for="item in materiaList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="materialCount" label="数量" align="center" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.materialCount" type="number" :disabled="popType == 1"
                          placeholder=""></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="batchNo" label="批次号" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.batchNo" placeholder="" :disabled="popType == 1"
                          style="width: 100%"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <!--                <el-button @click="handleEditConfigLine(scope.row,scope.$index)"-->
                <!--                           plain :icon="Edit">-->
                <!--                  编辑-->
                <!--                </el-button>-->
                <el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <el-dialog v-model="showDetail" :title="crudTitle + '入库单'" width="1000px">
      <el-form :model="formData" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="工序订单："> {{ formData.procedureOrderName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库："> {{ formData.targetWarehouseName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库库位："> {{ formData.targetStorageName || '--' }}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <div class="pageTableTitle">物料列表</div>
        </el-row>
        <el-row :gutter="10" style="padding: 10px">
          <el-table :data="formData.details" style="width:100% " height="calc(100vh - 600px)">
            <el-table-column label="序号" type="index" align="center" width="80"/>
            <el-table-column prop="materialName" label="物料名称" align="center"/>
            <el-table-column prop="materialCount" label="数量" align="center" width="150"/>
            <el-table-column prop="batchNo" label="批次号" align="center"/>
            <el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
              <template #header>
                <el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
              </template>
              <template #default="scope">
                <el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)"> 删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetail = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 点击入库弹窗 -->
    <el-dialog v-model="numberChangeShow" title="库存调整" width="1000px">
      <el-form :model="numberChangeRow" :rules="outInRules" ref="numberChangeRowRef" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="物料名称"> {{ numberChangeRow.materialName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号"> {{ numberChangeRow.batchNo || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位名称"> {{ numberChangeRow.storageName || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原数量"> {{ numberChangeRow.count || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调整数量" prop="laterCount" required>
              <el-input v-model="numberChangeRow.laterCount" type="number" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原因" prop="description">
              <el-input v-model="numberChangeRow.description" placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="numberChangeShow = false">取消</el-button>
          <el-button type="primary" @click="sumNumberChange(numberChangeRowRef)">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="二维码拆分" width="600px" v-model="qrCodeShow">
      <el-form label-width="auto">
        <el-form-item label="数量" required>
          <el-input-number v-model="qrCodeForm.count" :min="0" style="width: 50%;"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="qrCodeForm.description" :rows="2" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="qrCodeShow = false">取 消</el-button>
          <el-button type="primary" @click="doQrCodeSplit">确 定</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog title="追溯码修改" width="800px" v-model="qrChangeShow">
      <el-form label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号">
              {{ qrCodeForm.batchNo }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原追溯码">
              {{ qrCodeForm.traceabilityCode }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="追溯码">
              <el-input v-model="qrCodeForm.newTraceCode" placeholder="请输入追溯码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="qrChangeShow = false">取 消</el-button>
          <el-button type="primary" @click="quCodeChangeSubmint">确 定</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog title="成品包装打印" width="700px" v-model="finishedShow">
      <el-form label-width="80">
        <el-row>
          <el-col :span="8">
            <el-form-item label="数量">
              <el-input v-model="finishedProductForm.count" type="number " placeholder="请输入数量"
                        style="width: 200px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              <el-input v-model="finishedProductForm.description" placeholder="请输入备注" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="finishedShow = false">取 消</el-button>
          <el-button type="primary" @click="finishedSubmint">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="生产退库" width="500px" v-model="rollbackShow">
      <el-form label-width="auto">
        <el-form-item label="目标库位">
          <el-tree-select style="width: 400px" v-model="formRollback.wareId" :data="wareList" check-strictly clearable
                          filterable :render-after-expand="false" :props="{
              children: 'sonList',
              label: 'warehouseName',
              value: 'id',
            }" @change="wareChange2"/>
        </el-form-item>
        <el-form-item label="目标库位">
          <el-select v-model="formRollback.storageId2" placeholder="请选择" clearable filterable style="width: 400px">
            <el-option v-for="item in storageList2" :key="item.id" :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="退库备注">
          <el-input v-model="formRollback.remark" style="width: 400px" :rows="2" type="textarea"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rollbackShow = false">取 消</el-button>
          <el-button type="primary" @click="rollbackShowOK">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="编辑备注" width="500px" v-model="remarkEditShow">
      <el-form>
        <el-form-item label="">
          <el-input v-model="remarkForm.description" type="textarea" :rows="4" placeholder="请输入备注内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="remarkEditShow = false">取 消</el-button>
          <el-button type="primary" @click="saveRemark">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, onMounted, ref} from 'vue';
import type {FormRules} from 'element-plus';
import {ElMessage, ElMessageBox, FormInstance} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Plus, Refresh, Search} from '@element-plus/icons-vue';
import axios from 'axios';
import moment from 'moment';
import {EditPen} from '@element-plus/icons-vue';

const paginatedData = ref([]);
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});
const formRollback = ref({});
const rollbackShow = ref(false);
const materialStatusType = ref([
  {code: 0, description: '不可用'},
  {code: 1, description: '可用'},
  {code: 4, description: '不合格'},
  {code: 5, description: '报废'}
]);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};


// 数据定义
const remarkEditShow = ref(false);
const remarkForm = ref({
  id: '',
  description: ''
});

// 方法定义
const showRemarkEdit = (row) => {
  remarkForm.value = {
    id: row.id,
    description: row.description
  }
  remarkEditShow.value = true;
};

const saveRemark = () => {
  if (!remarkForm.value.id) {
    ElMessage.error('保存失败，缺少ID参数');
    return;
  }

  axiosInstance.put('/api/warehouseStorageMaterial/update', remarkForm.value)
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        ElMessage.success('备注保存成功');
        remarkEditShow.value = false;
        getList(); // 刷新列表
      })
      .catch(error => {
        ElMessage.error('保存备注失败');
        console.error(error);
      });
};

const formData = ref({
  planNo: '',
  name: '',
  planBeginTime: null,
  planEndTime: null,
  actualBeginTime: null,
  actualEndTime: null,
  organizationId: '',
  status: '0',
  type: '0'
});

const crudTitle = computed(() => {
  if (popType.value === 1) {
    return '查看';
  } else {
    return isEdit.value ? '编辑' : '新建';
  }
});

const showDetail = ref(false);


// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  currentPage.value = 1;
  localStorage.removeItem('inventoryDetailSearchParam');
  // currentPage.value = 1
  getList();
};

const procedureOrderList = ref({});
const wareList = ref({});
const storageList = ref({});
const storageList2 = ref([]);
const materiaList = ref({});
const showOutIn = ref(false);

const numberChangeRowRef = ref(null);
const outInRules = reactive<FormRules<numberChangeRow>>({
  laterCount: [
    {required: true, message: '请输入调整数量', trigger: 'blur'}
  ]
});

const materialStatusChange = (row, type) => {
  // 根据type获取描述
  const statusDescription = materialStatusType.value.find(item => item.code === type).description;

  // 显示确认对话框
  ElMessageBox.confirm(`是否改变物料状态为${statusDescription}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户确认后的操作
    axiosInstance.post('/api/warehouseStorageMaterial/updateMaterialStatus', {
      id: row.id,
      materialStatus: type
    })
        .then((res) => {
          if (res.code !== 200) {
            ElMessage.warning(res.message);
            return false;
          }
          ElMessage.success('操作成功');
          getList();
        });
  });
};
const handleAddConfigLine = () => {
  formData.value.details.push({
    materialId: null,
    materialCount: null,
    batchNo: null
  });
};


const outFatherInfo = ref({});
const showRollback = (row) => {
  formRollback.value = {
    ...row,
    targetStorageId: '',
    remark: ''

  };
  storageList2.value = [];
  rollbackShow.value = true;
};
const rollbackShowOK = () => {
  axiosInstance.post('/api/warehouseStorageMaterial/productionRetreatWarehouse', {
    targetStorageId: formRollback.value.storageId2,
    id: formRollback.value.id,
    remark: formRollback.value.remark
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        ElMessage.success('操作成功');
        rollbackShow.value = false;
        getList();
      });
};
const doOutIn = (row) => {
  numberChangeRow.value = JSON.parse(JSON.stringify(row));
  // this.materialCount = JSON.parse(JSON.stringify(param.materialCount))
  // 循环列表 找出子单据的父级
  // 提交时只提交父级和该条子单据

  for (const item of paginatedData.value) {
    if (item.children && item.children.length > 0) {
      for (const items of item.children) {
        if (items.id === row.id) {
          outFatherInfo.value = item;
          numberChangeRow.value.targetWarehouseId = item.targetWarehouseId;
          numberChangeRow.value.targetStorageId = item.targetStorageId;
          wareChange(item.targetWarehouseId);
        }
      }
    }
  }
  showOutIn.value = true;
};

const handleConfigDelete = (e) => {
  formData.value.details.splice(e, 1);
};

const materialStatusList = ref([
  {
    value: 0,
    label: '未加工'
  },
  {
    value: 1,
    label: '已加工'
  }
]);

const wareChange = (e, type) => {
  if (!type) {
    formData.value.targetStorageId = null;
  }
  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList.value = res.data.records;
        getList();
      });
};
const wareChange2 = (e, type) => {

  // storageList.value = {}
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        storageList2.value = res.data.records;
      });
};
const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const getSummaries = (param) => {
  const {columns, data} = param;
  const sums = [];

  // 初始化所有列的合计值为''
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    sums[index] = '';
  });

  // 计算数量列的合计值
  const countIndex = columns.findIndex(column => column.property === 'count');
  if (countIndex !== -1) {
    const values = data.map(item => Number(item.count));
    sums[countIndex] = values.reduce((prev, curr) => {
      const value = Number(curr);
      if (!isNaN(value)) {
        return prev + curr;
      } else {
        return prev;
      }
    }, 0).toFixed(2);
  }

  return sums;
};


const {proxy}: any = getCurrentInstance();

const qrCodeForm = ref({});
const qrCodeShow = ref(false);
const qrChangeShow = ref(false);
const qrCodeSplit = () => {
  qrCodeForm.value = {
    id: multipleSelection.value[0].id
  };
  qrCodeShow.value = true;
};

const qrCodeChange = () => {
  qrCodeForm.value = JSON.parse(JSON.stringify(multipleSelection.value[0]));
  qrChangeShow.value = true;
};

const finishedProductForm = ref({});
const finishedShow = ref(false);

const finishedProductShow = () => {
  finishedProductForm.value = JSON.parse(JSON.stringify(multipleSelection.value[0]));
  finishedShow.value = true;
};

const finishedSubmint = () => {
  const param = {
    id: finishedProductForm.value.id,
    count: finishedProductForm.value.count,
    description: finishedProductForm.value.description
  };
  axiosInstance.post('/api/warehouseStorageMaterial/updatePrint', param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        const param = multipleSelection.value.map(item => {
          return {
            id: item.id,
            registerName: item.registerName || null
          };
        });
        axiosInstance.post('/api/warehouseStorageMaterial/updateRegisterName', param)
            .then((resq) => {
              if (resq.code !== 200) {
                ElMessage.warning(resq.message);
                return false;
              }
              const templateName = 'test_print1/FinishedProductPackagingPrinting.cpt';
              proxy.$printClick(templateName, multipleSelection.value);
              getList();
              finishedShow.value = false;

            })
      });
};

const quCodeChangeSubmint = () => {
  if (!qrCodeForm.value.newTraceCode) {
    ElMessage.error('请输入追溯码');
    return false;
  }
  qrCodeForm.value.traceCode = qrCodeForm.value.traceabilityCode;
  axiosInstance.post('/api/traceCode/updateByBatchNoAndTraceCode', qrCodeForm.value)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        ElMessage.success('操作成功');
        qrChangeShow.value = false;
        getList();
      });
};

const qrCodePush = () => {
  // element 二次确认
  ElMessageBox.confirm('确定合并二维码？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id);
    axiosInstance.post('/api/warehouseStorageMaterial/qrCodeMerge', ids)
        .then((res) => {
          if (res.code !== 200) {
            ElMessage.warning(res.message);
            return false;
          }
          ElMessage.success('操作成功');
          getList();
        });
  });
};

const doQrCodeSplit = () => {
  console.log(qrCodeForm.value);

  if (!qrCodeForm.value.count) {
    ElMessage.error('请输入拆分数量');
    return false;
  }

  axiosInstance.post('/api/warehouseStorageMaterial/qrCodeSplit', qrCodeForm.value)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        ElMessage.success('操作成功');
        qrCodeShow.value = false;
        getList();
      });
};
// 箱码
const printBoxClick = () => {
  const templateName = 'test_print1/warehouseStorageMaterial.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};

const traceCodePrint = () => {
  console.log(multipleSelection.value)
  // [{"id":"123",'registerName":"456}]
  const param = multipleSelection.value.map(item => {
    return {
      id: item.id,
      registerName: item.registerName || null
    };
  });
  axiosInstance.post('/api/warehouseStorageMaterial/updateRegisterName', param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        const templateName = 'test_print1/traceCodePrints.cpt';
        proxy.$printClick(templateName, multipleSelection.value);
      })
};
const printClick = () => {
  const param = multipleSelection.value.map(item => {
    return {
      id: item.id,
      registerName: item.registerName || null
    };
  });
  axiosInstance.post('/api/warehouseStorageMaterial/updateRegisterName', param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        const batchNos = multipleSelection.value.map(item => item.batchNo);

        const firstTwoChars = batchNos[0].substring(0, 2);
        for (const batchNo of batchNos) {
          if (batchNo.substring(0, 2) !== firstTwoChars) {
            ElMessage.error('请选择同类型批次号');
            return; // 终止函数执行
          }
        }

        // 根据batchNo的前两个字母设置templateName
        const templateBaseName = 'test_print1/warehouseSupplementTemplate';
        const templateName = firstTwoChars === 'IN'
            ? `${templateBaseName}_IN.cpt`
            : `${templateBaseName}.cpt`;

        proxy.$printClick(templateName, multipleSelection.value);
      });

};

const getOption = () => {
  axiosInstance
      .post('/api/basedataMaterial/getAll', {}).then(res => {
    if (res.code == 200) {
      const list = res.data;
      const loop = [];
      for (const item of list) {
        loop.push(
            {
              value: item.id,
              label: item.materialName
            }
        );
      }
      materiaList.value = loop;
    }
  });
  axiosInstance.post('/api/planProcedureOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data;
        const loop = [];
        for (const item of list) {
          loop.push(
              {
                value: item.id,
                label: item.materialName
              }
          );
        }
        procedureOrderList.value = list;
      });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });

  // axiosInstance.post('/api/qualitySchemeTask/getPage', {})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //       storageList.value = res.data
  //     })
};


const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};

const typeList = ref([
  {label: '未完成', value: '0'},
  {label: '已完成', value: '1'}
]);

const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({status: 2});

// 新建记录
const handleAdd = () => {
  popType.value = 0;
  isEdit.value = false;
  formData.value = {
    details: [{
      materialId: null,
      materialCount: null,
      batchNo: null
    }]
  };
  showCrud.value = true;
};

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/warehouseStorageMaterial/pageByPojoExportExcel', {
    ...searchParam.value
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '库存详情' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


const popType = ref(0);//0 编辑 1 只读


const statusList = ref([
// 	{
// 	label: '不可用',
// 	value: 0
// },
  {
    label: '可用',
    value: 1
  }, {
    label: '运输中',
    value: 2
  }, {
    label: '生产锁定',
    value: 3
  }, {
    label: '不合格',
    value: 4
  }, {
    label: '报废',
    value: 5
  }, {
    label: '待检',
    value: 6,
    disabled: true
  }
]);

const formatStatus = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '不可用';
    case 1:
      return '可用';
    case 2:
      return '运输中';
    case 3:
      return '生产锁定';
    case 4:
      return '不合格';
    case 5:
      return '报废';
  }
};

const formatProcessingAttributes = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '未加工';
    case 1:
      return '已加工';

  }
};

const rejectShow = ref({});

// 编辑记录
const
    handleEdit = (row: any, type) => {
      // console.log(row,'czqRow')
      ElMessageBox.prompt('请输入驳回原因', '驳回', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      })
          .then(({value}) => {
            row.remark = value;
            const param = {
              id: row.materialTransferOrderId,
              code: row.orderNo,
              details: [row],
              tasks: [row]
            };
            axiosInstance.post('/api/warehouseMaterialTransferOrder/reject', param).then((res) => {
              if (res.code === 200) {
                getList();
                ElMessage.success('驳回成功');

              } else {
                ElMessage.warning(res.message);
              }
            });
          });
      // isEdit.value = true;
      // formData.value = {...row};
      // axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
      //   if (res.code !== 200) {
      //     ElMessage.warning(res.message);
      //     return false;
      //   }
      //   formData.value.details = res.data.children
      //   if (type) {
      //     // 查看详情
      //     popType.value = type
      //     showDetail.value = true
      //   } else {
      //     // 编辑
      //     popType.value = 0
      //     showCrud.value = true;
      //   }
      //   wareChange(e.targetWarehouseId)
      // })
    };


// 保存记录
const handleSave = async () => {
  const param = formData.value;
  if (param.details.length == 0) {
    ElMessage.warning('请选择物料');
    return false;
  }
  for (const item of param.details) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料');
      return false;
    }
    if (!item.materialCount || item.materialCount === 0) {
      ElMessage.warning('请输入数量');
      return false;
    }


  }
  axiosInstance.post('/api/warehouseMaterialTransferOrder/save', {...param, ...transferType.value})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showCrud.value = false;
        getList();
      });
};

// 展开行处理
const expandedRowKeys = ref<string[]>([]);
const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', {id: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    paginatedData.value = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: res.data.children};
      }
      return item;
    });
  });
  // axiosInstance.post('/api/报工总数打印/getAll', {planId: row.id})
  //     .then(res => {
  //       if (res.code !== 200) {
  //         ElMessage.error(res.message);
  //         return false
  //       }
  //
  //       .value = res.data
  //     });

  // ProductionPlanDetailApi().then((res) => {
  //   if (res.code !== 200) {
  //     ElMessage.warning(res.message);
  //     return false;
  //   }
  //   const listGroup = paginatedData.value.map((item) => {
  //     if (item.id === row.id) {
  //       return {...item, children: res.data.records};
  //     }
  //     return item;
  //   });
  //   paginatedData.value = listGroup;
  // });
};

const pageTotal = ref(0);

const loadCache = () => {
  const inventoryDetailSearchParam = localStorage.getItem('inventoryDetailSearchParam');
  let parsedParam = {};

  if (inventoryDetailSearchParam) {
    try {
      parsedParam = JSON.parse(inventoryDetailSearchParam);
    } catch (error) {
      console.error('Error parsing inventoryDetailSearchParam:', error);
    }
  }
  searchParam.value = parsedParam;
  if (searchParam.value.warehouseId) {
    wareChange(searchParam.value.warehouseId);
  }
};


// 获取列表
const getList = async () => {
  localStorage.setItem('inventoryDetailSearchParam', JSON.stringify(searchParam.value));
  console.log(searchParam.value.batchNo);
  axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', {
    current: currentPage.value,
    pageSize: pageSize.value,
    ...searchParam.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const numberChangeRow = ref({});
const numberChangeShow = ref(false);
const showNumberChange = (row) => {
  numberChangeRow.value = JSON.parse(JSON.stringify(row));
  numberChangeShow.value = true;
};

const sumNumberChange = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (numberChangeRow.value.laterCount == 0) {
        ElMessageBox.confirm(`数量为0会删除该条记录，是否继续？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          repertoryTransferAdd();
        });
      } else {
        repertoryTransferAdd();
      }

    }
  });
};

const repertoryTransferAdd = () => {
  let param = JSON.parse(JSON.stringify(numberChangeRow.value));
  param.warehouseStorageMaterialId = param.id;
  delete param.id;
  axiosInstance.post('/api/repertoryTransferAdd/save', param)
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
        numberChangeShow.value = false;
        getList();
      });
};

onMounted(() => {
  loadCache();
  getList();
  getOption();
});
</script>
<style scoped lang="scss">
.canChange {
  color: #00aaff;
  cursor: pointer;
}

.canChange {
  color: #00aaff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    text-decoration: underline;
  }

  .el-icon {
    font-size: 16px;
  }
}
</style>
